<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Area;
use app\common\tool\Result;
use think\exception\ValidateException;
use app\common\model\Address as AddressModel;
use think\Response;

class Address extends Base
{

    public function index(): Response
    {
        try {
            $map = ['uid' => $this->user->id, 'is_del' => 0];

            $list = AddressModel::getPageList($map, 'id,nickname,tel,province,city,district,details,default', $this->getPage(),
                    $this->getLimit(), false, ['p', 'c', 'd']);

            // $list = AddressModel::getPageList($map, false, 'create_time', ['p', 'c', 'd'],
            //     'id,nickname,tel,province,city,district,details,default');
            foreach ($list['data'] as &$v) {
                $v->province = $v->p->title;
                $v->city = $v->c->title;
                $v->district = $v->d->title;

                $v->province_id = $v->p->id;
                $v->city_id = $v->c->id;
                $v->district_id = $v->d->id;

                $v->province_code = $v->p->code;
                $v->city_code = $v->c->code;
                $v->district_code = $v->d->code;
                unset($v->p);
                unset($v->c);
                unset($v->d);
            }
            return Result::fastReturn($list);
        } catch (Exception $e) {
            return Result::fail($e->getError());
        }

    }

    public function edit($id): Response
    {
        $info = AddressModel::with(['p', 'c', 'd'])->where('id', $id)
            ->field('id,nickname,tel,province,city,district,details,default')->find();
        unset($info->province);
        unset($info->city);
        unset($info->district);
        return Result::success('success', $info);
    }

    public function save(): Response
    {
        $param = $this->request->post('', '', $this->filter);
        try {
            $this->validate($param, 'Address');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
        return Result::fastReturn(AddressModel::add($param, $this->user));

    }

    public function delete($id): Response
    {
        return json(AddressModel::edit($id, $this->user));
    }

    public function getArea($id, $level = 0): Response
    {
        return Result::success('success', Area::getArea($id ?: 100000, $level));
    }

    public function default(): Response
    {
        return Result::fastReturn(AddressModel::default($this->request->post('id'), $this->user));
    }

}

